package com.ygl.gateway.config;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.Executor;

@Component
public class DynamicRouteServiceImplByNacos implements ApplicationEventPublisherAware {

    @Autowired
    private DynamicRouteServiceImpl dynamicRouteService;
    @Autowired
    private AppConfig appConfig;

    /**
     * 监听Nacos Server下发的动态路由配置
     */
    @PostConstruct
    public void dynamicRouteByNacosListener (){
        try {
            String dataId= "gateway-router";
            String group = "DEV_GROUP";
            Properties properties = new Properties();
            properties.put(PropertyKeyConst.SERVER_ADDR, appConfig.getServerAddr());
            properties.put(PropertyKeyConst.NAMESPACE, appConfig.getNamespace());
            ConfigService configService=NacosFactory.createConfigService(properties);
            String content = configService.getConfig(dataId, group, 5000);
            System.out.println(content);
            List<RouteDefinition> routeDefinitions = JSONArray.parseArray(content, RouteDefinition.class);
            dynamicRouteService.updateList(routeDefinitions);
            configService.addListener(dataId, group, new Listener()  {
                @Override
                public void receiveConfigInfo(String configInfo) {
                    List<RouteDefinition> routeDefinitions = JSONArray.parseArray(configInfo, RouteDefinition.class);
                    dynamicRouteService.updateList(routeDefinitions);
                }
                @Override
                public Executor getExecutor() {
                    return null;
                }
            });
        } catch (NacosException e) {
            //todo 提醒:异常自行处理此处省略
        }
    }

    private ApplicationEventPublisher applicationEventPublisher;
    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
        this.applicationEventPublisher = applicationEventPublisher;
    }
}
